package com.vmusic.data;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 生成音乐日志文件
 * 
 * @author jiaxiao
 * 
 */
public class MusicLogData extends MakeData {
	/**
	 * 字段分隔符
	 */
	public static final String COL_SPLIT = "	";
	/**
	 * 生成文件字符集编码
	 */
	public static final String CHAR_CODE = "UTF-8";
	private static Random r = new Random();

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			createData("D://vMusicLog.txt", 5000000, true);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 随机生成用户ID，范围 10000-19999
	 * 
	 * @return
	 */
	private static String randomCreateUserId() {
		return 10000 + r.nextInt(10000) + "";
	}

	/**
	 * 生成操作类型 0,1
	 * 
	 * @return
	 */
	private static String randomCreateOperateType() {
		return r.nextInt(2) + "";
	}

	/**
	 * 1-399 六位
	 * 
	 * @return
	 */
	private static String randomCreateSongId() {
		int id = r.nextInt(399) + 1;
		String sId = "";
		if (id < 10) {
			sId = "00000" + id;
		} else if (id < 100) {
			sId = "0000" + id;
		} else {
			sId = "000" + id;
		}
		return sId;

	}

	public static void createData(String filePath, int num, boolean isAppend)
			throws IOException {
		File file = new File(filePath);
		long begin = System.currentTimeMillis();
		List<String> lines = new ArrayList<String>();
		for (int i = 0; i < num; i++) {
			String data = CreateDateTimeString() + COL_SPLIT
					+ randomCreateOperateType() + COL_SPLIT
					+ randomCreateUserId() + COL_SPLIT + randomCreateSongId();
			lines.add(data);
			/**
			 * 每1万条时写入文件
			 */
			if (lines != null && lines.size() > 10000 && i < num - 1) {
				org.apache.commons.io.FileUtils.writeLines(file, CHAR_CODE,
						lines, isAppend);
				lines = new ArrayList<String>();
			}
		}

		if (lines != null && lines.size() > 0) {
			org.apache.commons.io.FileUtils.writeLines(file, CHAR_CODE, lines,
					isAppend);
		}
		long cost = System.currentTimeMillis() - begin;
		System.out.println("生成数据完毕,耗时:" + cost + " 毫秒.");
	}
}
